﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IndyMosaic.Models.Syndication;

namespace IndyMosaic.Models.Blog
{
    public class BlogRepository : IBlogRepository
    {
        private BlogDataContext context;

        public BlogRepository()
        {
            context = new BlogDataContext();
        }


        #region IBlogRepository Members
        public Entry GetEntry(int id)
        {
            return context.Entries.SingleOrDefault(be => be.ID == id);
        }
        public IQueryable<Entry> ListAllEntries()
        {
            var entries = from be in context.Entries
                          where be.DatePublished != null
                          select be;
            return entries.OrderByDescending(e => e.DatePublished);
        }

        public IQueryable<Entry> ListAllByAuthor(Guid authorID)
        {
            var entries = from be in context.Entries
                          where be.UserID == authorID
                          select be;
            return entries.OrderByDescending(e => e.DatePublished);
        }


        public IQueryable<Entry> ListLatestTopNEntries(int numberOfEntries)
        {
            var entries = from be in context.Entries
                          where be.DatePublished != null
                          select be;
            return entries.OrderByDescending(e => e.DatePublished).Take(numberOfEntries);

        }
        public void Add(Entry entry)
        {
            context.Entries.InsertOnSubmit(entry);
        }
        public void Add(Comment comment)
        {
            context.Comments.InsertOnSubmit(comment);
        }
        public void Save()
        {
            context.SubmitChanges();
        }

        public string GetFeed(IEnumerable<Entry> entries, string baseUrl, System.Web.Mvc.UrlHelper urlHelper)
        {
            return Feed.GetFeed("Mosaic Church Blog", "Blog for Mosaic Church of Indianapolis, IN", entries, baseUrl, urlHelper).GetRss20Feed();
        }

        public Comment GetComment(int commentID)
        {
            return context.Comments.SingleOrDefault(c => c.ID == commentID);
        }
        #endregion
    }

}